package com.zsinfo.guoss.supplier.fragment;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.netcenter.Event.Response;
import com.example.netcenter.NetCenter;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.example.netcenter.bean.HeadBean;
import com.example.netcenter.bean.ResultsData;
import com.example.netcenter.bean.SupplierAccountBean;
import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.activity.BillingListActivity;
import com.zsinfo.guoss.supplier.activity.FruitOfferListActivity;
import com.zsinfo.guoss.supplier.activity.MarginActivity;
import com.zsinfo.guoss.supplier.activity.NewProductActivity;
import com.zsinfo.guoss.supplier.activity.NewsActivity;
import com.zsinfo.guoss.supplier.activity.SettingActivity;
import com.zsinfo.guoss.supplier.activity.UserInfoActivity;
import com.zsinfo.guoss.supplier.base.BaseFragment;
import com.zsinfo.guoss.supplier.customize.ActionSheetDialog;
import com.zsinfo.guoss.supplier.customize.CircleImageView;
import com.zsinfo.guoss.supplier.utils.CommentUtil;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;
import com.zsinfo.guoss.supplier.utils.UIUtils;
import com.zsinfo.guoss.supplier.utils.UploadAsyncTask;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    private ImageView iv_my_message_dian;
    private LinearLayout ll_news, ll_kf;
    private LinearLayout ll_china_margin, ll_import_margin, ll_my_new, ll_quotation_record, ll_billing_details, ll_settings;
    private LinearLayout ll_edit_userinfo;
    private CircleImageView civ_headimg;
    private TextView tv_username, tv_website;
    @BindView(R.id.tv_chinaDeposit)
    TextView tv_chinaDeposit;
    @BindView(R.id.tv_importDeposit)
    TextView tv_importDeposit;

    String imagePath = "";

    public MineFragment() {
        // Required empty public constructor
    }

    @Override
    protected int getContentLayoutRes() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(View view) {
        iv_my_message_dian = view.findViewById(R.id.iv_my_message_dian);
        ll_news = view.findViewById(R.id.ll_news);
        ll_kf = view.findViewById(R.id.ll_kf);

        ll_china_margin = view.findViewById(R.id.ll_china_margin);
        ll_import_margin = view.findViewById(R.id.ll_import_margin);
        ll_my_new = view.findViewById(R.id.ll_my_new);
        ll_quotation_record = view.findViewById(R.id.ll_quotation_record);
        ll_billing_details = view.findViewById(R.id.ll_billing_details);
        ll_settings = view.findViewById(R.id.ll_settings);
        ll_edit_userinfo = view.findViewById(R.id.ll_edit_userinfo);
        civ_headimg = view.findViewById(R.id.civ_headimg);
        tv_username = view.findViewById(R.id.tv_username);
        tv_website = view.findViewById(R.id.tv_website);

        ll_news.setOnClickListener(this);
        ll_kf.setOnClickListener(this);
        ll_china_margin.setOnClickListener(this);
        ll_import_margin.setOnClickListener(this);
        ll_my_new.setOnClickListener(this);
        ll_quotation_record.setOnClickListener(this);
        ll_billing_details.setOnClickListener(this);
        ll_settings.setOnClickListener(this);
        ll_edit_userinfo.setOnClickListener(this);
        civ_headimg.setOnClickListener(this);

        initData();
    }

    /**
     * 网络请求，显示数据
     */
    private void initData() {

    }


    @Override
    public void onResume() {
        super.onResume();

        getMarginAccount();

        getNewsCount();

        //显示头像，姓名，站点
        String headImage = "";
        if (SharedPreferencesUtil.getFaceImg().contains("http")) {
            headImage = SharedPreferencesUtil.getFaceImg();
        } else {
            headImage = "http://" + SharedPreferencesUtil.getFaceImg();

        }

        Glide.with(context).load(headImage).into(civ_headimg);
        tv_username.setText(SharedPreferencesUtil.getFirmName());
        tv_website.setText(SharedPreferencesUtil.getwebsiteName());
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.ll_edit_userinfo:
                //个人资料
                startActivity(new Intent(context, UserInfoActivity.class));
                break;
            case R.id.civ_headimg:
                //Dialog修改头像
                choosePictureDialog();
                break;
            case R.id.ll_news:
                //消息中心
                startActivity(new Intent(context, NewsActivity.class));
                break;
            case R.id.ll_kf:
                //拨打电话
                final String phone = "400-0160-682";
                AlertDialog.Builder dialog = new AlertDialog.Builder(context);
                dialog.setTitle("提示")
                        .setMessage("确定拨打电话：" + phone + "吗？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                dialog.dismiss();
                            }
                        })
                        .show();
                break;
            case R.id.ll_china_margin:
                //国产保证金入口
                intent = new Intent(context, MarginActivity.class);
                intent.putExtra("type", 1);
                startActivity(intent);
                break;
            case R.id.ll_import_margin:
                //进口类保证金入口
                intent = new Intent(context, MarginActivity.class);
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
            case R.id.ll_my_new:
                //我的上新
                startActivity(new Intent(context, NewProductActivity.class));
                break;
            case R.id.ll_quotation_record:
                //报价记录
                startActivity(new Intent(context, FruitOfferListActivity.class));
                break;
            case R.id.ll_billing_details:
                //账单明细
                startActivity(new Intent(context, BillingListActivity.class));
                break;
            case R.id.ll_settings:
                //设置
                startActivity(new Intent(context, SettingActivity.class));
                break;
        }
    }

    /**
     * 获取保障金信息
     */
    private void getMarginAccount(){
        new NetCenter().GetNetCenter(getActivity(),
                RetrofitBuilder.CreateApi().SUPPLIER_ACCOUNT(ConstantsCode.supplier_account,
                        SharedPreferencesUtil.getID()), new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        //保证金
                        ResultsData<SupplierAccountBean> resultsData = (ResultsData<SupplierAccountBean>) data;
                        SupplierAccountBean supplierAccountBean = resultsData.getData();
                        tv_chinaDeposit.setText(supplierAccountBean.getDomesticDeposit()+""); //总金额
                        tv_importDeposit.setText(supplierAccountBean.getImportDeposit()+"");
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showToast(errorBean.getMsg());
                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    /**
     * 获取未度消息数量
     */
    private void getNewsCount(){
        new NetCenter().GetNetCenter(RetrofitBuilder.CreateApi().MSG_COUNT(
                ConstantsCode.supplier_msg_count,
                SharedPreferencesUtil.getID()),
                new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());  //{"statusCode":"100000","statusStr":"请求成功","data":0}
                        ResultsData<Integer> resultsData = (ResultsData<Integer>) data;
                        Integer count = resultsData.getData();
                        if (count > 0){
                            iv_my_message_dian.setVisibility(View.VISIBLE);
                        } else {
                            iv_my_message_dian.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    /**
     * 选择拍照，图库
     */
    private void choosePictureDialog() {
        new ActionSheetDialog(context)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("照相机", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (AndPermission.hasPermission(context, Manifest.permission.CAMERA)) {
                                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                        File file = new File(
                                                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath(),
                                                System.currentTimeMillis() + ".png");
                                        Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".Fileprovider",
                                                file);
                                        Intent intent = new Intent();
                                        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                                        imagePath = file.getAbsolutePath();
                                        startActivityForResult(intent, 100);
                                    }
                                } else {
                                    AndPermission.with((Activity) context)
                                            .permission(Manifest.permission.CAMERA)
                                            .requestCode(10000)
                                            .send();
                                }
                            }
                        })
                .addSheetItem("本地相册", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                if (AndPermission.hasPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                                    Intent intent = new Intent(
                                            Intent.ACTION_PICK,
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    intent.setDataAndType(
                                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                            "image/*");
                                    startActivityForResult(intent, 200);
                                } else {
                                    AndPermission.with((Activity) context)
                                            .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            .requestCode(20000)
                                            .send();
                                }
                            }
                        }).show();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) {
                imagePath = UIUtils.saveBitmapP(imagePath, 200);
                if (!TextUtils.isEmpty(imagePath)) {

                } else {
                    CommentUtil.showSingleToast("");
                }
            } else if (requestCode == 200) {
                if (data != null) {
                    Uri uri = data.getData();
                    Cursor cursor = context.getContentResolver()
                            .query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    imagePath = cursor.getString(1);
                    cursor.close();
                    imagePath = UIUtils.saveBitmapP(imagePath, 200);
                    List<String> imagePaths = new ArrayList<>();
                    imagePaths.add(imagePath);
                    new UploadAsyncTask("png", context,
                            new UploadAsyncTask.Callback() {
                                @Override
                                public void send(String result) {
                                    changeHeadImg(result);
                                }
                            }).execute(imagePath);

                } else {
                    CommentUtil.showSingleToast("网络链接异常，清检查网络后再试");
                }
            } else if (requestCode == 1) {
//                N_MainActivity.this.getSupportFragmentManager().beginTransaction().replace(R.id.layout, new Fragment_Mine()).commit();
            } else {
                CommentUtil.showSingleToast("没有获取到您所选择的图片");
            }
        }
    }

    /**
     * 更改头像
     * @param result
     */
    private void changeHeadImg(String result) {
        new NetCenter().GetNetCenter(context, RetrofitBuilder.CreateApi().UpLoadHeadImage("face_img_upload", SharedPreferencesUtil.getID(), "http://" + result), new Response() {
            @Override
            public void OK(Object data) {

                HeadBean registerBean = (HeadBean) data;

                if (registerBean.getData().getFaceImg().contains("http")) {

                    Glide.with(context).load(registerBean.getData().getFaceImg()).into(civ_headimg);

                } else {

                    Glide.with(context).load("http//" + registerBean.getData().getFaceImg()).into(civ_headimg);

                }

                SharedPreferencesUtil.setFaceImg(registerBean.getData().getFaceImg());

                showToast("上传成功");

            }

            @Override
            public void Fail(Throwable e) {
                Log.e("Conker", "OK: " + e);
            }

            @Override
            public void complete() {

            }
        });

    }

}
